/**
 * synclick同步点击事件
 * @param
 * options = {
 * 		//参数传入$.ajax({});
 * 		prepareData: function(){
 * 			//return the data for post request.
 * 		},
 * 		waitingClass: '', 
 * 		once: 'false',  //only click one
 * 		delay: 2, // delay seconds for next click
 * }
 * @author  tanggf
 */
(function($){
	$.fn.synclick = function(options){
		options = $.extend({
			trigger: 'click',
			once: false,
			delay: 2,
			prepareData: function(){return null;}
		}, options);
		
		return this.each(function(){
			_get_synclick_(this, options);
		});
	};
	
	function _get_synclick_(ele, options){
		var $this = $(ele);
		var sc = $this.data("_smr_synclick_");
		if(sc == null){
			sc = new _Synclick_(ele, options);
			$this.data("_smr_synclick_", sc);
		}
		return sc;
	}
	
	function _Synclick_(ele, options){
		this.$ele = $(ele);
		this.options = options;
		this._init_();
		this.clicked = false;
	}
	
	_Synclick_.prototype = {
			_init_: function(){				
				var self = this;
				this.$ele.bind(this.options.trigger, function(){
					self._handle_click();		
				});
			},
			
			_handle_click: function(){
				if(this.clicked){
					return;
				}
				var data = this.options.prepareData();
				if( ! data){
					return;
				}
				this.options.data = data;				
				if(this._before() === false){
					return;
				}
				
				var old = this.options.complete;
				var self = this;
				this.options.complete = function(jqXHR, textStatus){
					if(old){
						old(jqXHR, textStatus);
					}
					self._complete();
				};
				
				$.ajax(this.options);
			},
			
			_before: function(){
				this.$ele.css({'cursor': 'wait'});
				if(this.options.waitingClass){
					this.$ele.addClass(this.options.waitingClass);
				}
				var v = true;
				if(this.options.beforeSend){
					v = this.options.beforeSend();					
				}
				if( ! v){
					this._the_end();
				}else{
					this.clicked = true;
				}				
			},
			
			_complete: function(){
				var opts = this.options;
				var self = this;
				if(opts.once){
					return;
				}
				
				if(opts.delay > 0){
					setTimeout(function(){
						self._the_end();
					}, opts.delay * 1000);
				}else{
					this._the_end();
				}				
			},
			
			_the_end: function(){
				this.clicked = false;
				this.$ele.css({'cursor': 'pointer'});
				if(this.options.waitingClass){
					this.$ele.removeClass(this.options.waitingClass);
				}
			}
	};
})(jQuery);